<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '订单详情',
  },
}
</route>
<script lang="ts" setup>
import { onBeforeUnmount, ref, computed } from 'vue'
import { OrderApi, OrderStatusMap } from '@/service/order/order'
import { useMessage, useToast } from 'wot-design-uni'
import { createDebounceFunc } from '@/utils/index'
import { PayApi } from '@/service/pay/pay'
import { OrderInfoVo, OrderItem, OrderStatusDto } from '@/service/order/order.d'
import { OrderStatusEnum, PayTypeEnum } from '@/service/order/orderEnum.d'

const message = useMessage()
const toast = useToast()
const orderId = ref(null)
const orderInfo = ref<OrderInfoVo>({} as OrderInfoVo)
const orderItemList = ref<OrderItem[]>([])
let timer = null
onLoad((options) => {
  console.log(options.orderId)
  if (options.orderId) {
    orderId.value = options.orderId
  } else {
    uni.showToast({
      title: '缺少参数',
      icon: 'none',
    })
    timer = setTimeout(() => {
      uni.switchTab({
        url: '/pages/index/index',
      })
    })
  }
})
const showAll = ref(false)
const couponDiscount = computed(() => {
  return orderItemList.value
    .filter((item) => {
      // 数值有效性验证
      return !Number.isNaN(item.discountPrice) && item.discountPrice > 0
    })
    .reduce((acc, cur) => {
      // 精度处理：保留两位小数
      return acc + Number(cur.discountPrice.toFixed(2))
    }, 0)
})
onShow(() => {
  OrderApi.getDetail(orderId.value).then(({ code, data }) => {
    if (code === 200 && data) {
      orderInfo.value = data
      orderItemList.value = data.orderItemList || []
    }
  })
})
const promotionDiscount = computed(() => {
  return orderItemList.value
    .filter((item) => {
      // 数值有效性验证
      return (
        !Number.isNaN(item.skuMarketPrice) &&
        item.skuMarketPrice > 0 &&
        !Number.isNaN(item.skuPrice) &&
        item.skuPrice > 0
      )
    })
    .reduce((acc, cur) => {
      // 精度处理：保留两位小数
      return acc + Number(((cur.skuMarketPrice - cur.skuPrice) * cur.skuNum).toFixed(2))
    }, 0)
})
const goRefundPay = () => {
  uni.navigateTo({
    url: `/pages/order/refundPay?orderId=${orderInfo.value.id}`,
  })
}
const handelWaitComment = (orderId: number, type: string = 'insert') => {
  uni.navigateTo({ url: `/pages/goods/comment/addComment?orderId=${orderId}&type=${type}` })
}
const closeOrder = (orderId: number) => {
  if (orderId <= 0) return toast.show('非法点击')
  message
    .confirm({
      msg: '确定要取消订单吗？',
      title: '温馨提示',
    })
    .then(() => {
      uni.navigateTo({ url: `/pages/order/cancelOrder?orderId=${orderId}` })
    })
    .catch(() => {})
}
const deleteOrder = (orderId: number) => {
  if (orderId <= 0) return toast.show('非法点击')
  message
    .confirm({
      msg: '确定要删除订单吗？删除后无法恢复！',
      title: '温馨提示',
    })
    .then(() => {
      OrderApi.deleteOrder(orderId)
        .then((res) => {
          if (res.code === 200) {
            toast.show('删除成功')
            uni.navigateBack()
          }
        })
        .catch(() => {
          toast.show('删除失败')
        })
    })
    .catch(() => {})
}

const confirmReceipt = (orderId: number) => {
  if (orderId <= 0) return toast.show('非法点击')
  message
    .confirm({
      msg: '确定要收货吗？',
      title: '温馨提示',
    })
    .then(() => {
      const obj: OrderStatusDto = {
        orderId,
        status: OrderStatusEnum.WAIT_COMMENT,
      }
      OrderApi.updateOrderStatus(obj)
        .then((res) => {
          if (res.code === 200) {
            toast.show('收货成功')
          }
        })
        .catch(() => {
          toast.show('收货失败')
        })
    })
    .catch(() => {})
}

const { execute: goPay } = createDebounceFunc(
  async (orderNo: string) => {
    console.log(orderNo)
    const res = await PayApi.aliPay(orderNo)
    document.querySelector('body').innerHTML = res as unknown as string
    document.forms[0].submit()
  },
  1000,
  { leading: true, trailing: false },
)
// 销毁前清理
onBeforeUnmount(() => {
  clearInterval(timer)
})
</script>
<template>
  <view class="order-detail">
    <!-- 订单状态卡片 -->
    <view class="status-card section">
      <view class="status-content">
        <view class="status-info">
          <view class="status-title">
            <wd-icon name="success" size="48rpx" color="#fff" />
            <text class="status-title-text">
              {{ OrderStatusMap[Number(orderInfo.orderStatus)] }}
            </text>
          </view>
          <view class="status-lable">
            <!-- <text class="status-lable-text">交易成功</text> -->
          </view>
        </view>
        <wd-divider custom-class="status-divider"></wd-divider>
        <view class="status-meta">
          <view
            class="status-item"
            @click.stop="closeOrder(orderInfo.id)"
            v-if="orderInfo.orderStatus === OrderStatusEnum.WAIT_PAY"
          >
            <view class="action-icon tabbar-quxiao iconfont"></view>
            <view class="action-text">取消订单</view>
          </view>
          <view
            class="status-item"
            @click="handelWaitComment(orderInfo.id)"
            v-if="orderInfo.orderStatus === OrderStatusEnum.WAIT_COMMENT"
          >
            <view class="action-icon iconfont tabbar-pingjia"></view>
            <view class="action-text">去评价</view>
          </view>
          <!-- <view
            class="status-item"
            @click="handelWaitComment(orderInfo.id, 'readOnly')"
            v-if="orderInfo.orderStatus === OrderStatusEnum.COMPLETED"
          >
            <view class="action-icon iconfont tabbar-pingjia"></view>
            <view class="action-text">已经评价</view>
          </view> -->
          <view
            class="status-item"
            @click.stop="goPay(orderInfo.orderNo)"
            v-if="orderInfo.orderStatus === OrderStatusEnum.WAIT_PAY"
          >
            <view class="action-icon iconfont tabbar-daifukuan"></view>
            <view class="action-text">去支付</view>
          </view>
          <view
            class="status-item"
            @click.stop="confirmReceipt(orderInfo.id)"
            v-if="orderInfo.orderStatus === OrderStatusEnum.ALREADY_DELIVER"
          >
            <view class="action-icon iconfont tabbar-daishouhuo"></view>
            <view class="action-text">确认收货</view>
          </view>
          <view
            class="status-item"
            @click="deleteOrder(orderInfo.id)"
            v-if="
              orderInfo.orderStatus === OrderStatusEnum.CANCEL ||
              orderInfo.orderStatus === OrderStatusEnum.COMPLETED ||
              orderInfo.orderStatus === OrderStatusEnum.REFUNDED
            "
          >
            <view class="action-icon iconfont tabbar-shanchu"></view>
            <view class="action-text">删除订单</view>
          </view>
          <view
            class="status-item"
            @click="goRefundPay"
            v-if="
              orderInfo.orderStatus === OrderStatusEnum.ALREADY_DELIVER ||
              orderInfo.orderStatus === OrderStatusEnum.WAIT_DELIVER ||
              orderInfo.orderStatus === OrderStatusEnum.WAIT_COMMENT ||
              orderInfo.orderStatus === OrderStatusEnum.COMPLETED
            "
          >
            <view class="action-icon iconfont tabbar-tuiketuikuan"></view>
            <view class="action-text">申请退款</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 地址展示卡片 -->
    <view class="address-section section">
      <view class="address-card">
        <view class="address-header">
          <wd-icon name="location" size="32rpx" />
          <text class="title">收货地址</text>
        </view>
        <view class="address-body">
          <text class="name">{{ orderInfo.receiverName }}</text>
          <text class="phone">{{ orderInfo.receiverPhone }}</text>
          <text class="detail">
            {{
              orderInfo.receiverProvince +
              orderInfo.receiverCity +
              orderInfo.receiverDistrict +
              orderInfo.receiverAddress
            }}
          </text>
        </view>
      </view>
    </view>

    <view class="goods-section section">
      <view class="section-title">
        商品清单（{{ orderItemList.length > 0 ? orderItemList.length : 0 }}）
      </view>
      <view class="goods-list">
        <view
          class="goods-item"
          v-for="(item, index) in showAll ? orderItemList : orderItemList.slice(0, 3)"
          :key="index"
        >
          <image :src="item.thumbImg" class="goods-thumb" />
          <view class="goods-info">
            <view class="goods-info-one">
              <text class="name">{{ item.skuName }}</text>
              <view class="goods-info-price">
                <text class="sale-price">{{ item.skuPrice }}</text>
                <text class="market-price">{{ item.skuMarketPrice }}</text>
              </view>
            </view>
            <text class="quantity">x{{ item.skuNum }}</text>
          </view>
        </view>
      </view>
      <!-- 展开按钮 -->
      <view v-if="orderItemList.length > 3" class="expand-btn" @click="showAll = !showAll">
        {{ showAll ? '收起' : '展开更多' }}
        <wd-icon :name="showAll ? 'arrow-up' : 'arrow-down'" />
      </view>

      <!-- 完全复用的优惠信息 -->
      <view class="discount-info">
        <view class="discount-item">
          <view>
            <text class="iconfont icon-cuxiao" style="margin-right: 10rpx"></text>
            <text>促销优惠</text>
          </view>
          <text class="value">-¥{{ promotionDiscount }}</text>
        </view>
        <view class="discount-item">
          <view>
            <text class="iconfont icon-diyongquan" style="margin-right: 10rpx"></text>
            <text>优惠券</text>
          </view>
          <text class="value">-¥{{ couponDiscount }}</text>
        </view>
        <view class="total-line">
          <text>已优惠 ¥{{ orderInfo.couponAmount + promotionDiscount }}</text>
          <text class="total">合计：{{ orderInfo.totalAmount }}</text>
        </view>
      </view>
    </view>
    <view class="order-section section">
      <view class="section-title">订单信息</view>
      <view class="order-info">
        <view class="custom-cell-group">
          <view class="custom-cell">
            <text class="cell-title">订单编号</text>
            <text class="cell-value">{{ orderInfo.orderNo }}</text>
          </view>
          <view class="custom-cell">
            <text class="cell-title">下单时间</text>
            <text class="cell-value">{{ orderInfo.createTime }}</text>
          </view>
          <view class="custom-cell">
            <text class="cell-title">支付方式</text>
            <text class="cell-value" v-if="orderInfo.payType === PayTypeEnum.ALIPAY">支付宝</text>
            <text class="cell-value" v-if="orderInfo.payType === PayTypeEnum.WXPAY">微信支付</text>
            <text class="cell-value" v-if="orderInfo.payType === PayTypeEnum.BALANCE">余额</text>
          </view>
          <view class="custom-cell">
            <text class="cell-title">留言备注</text>
            <text class="cell-value">{{ orderInfo.remark }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.order-detail {
  box-sizing: border-box;
  width: 750rpx;
  height: auto;
  padding: 20rpx;
  background-color: #f5f5f5;

  background-image: linear-gradient(to bottom, #ff5f15 0%, #f5f5f5 100%);
  background-repeat: no-repeat;
  background-size: 100% 600rpx;
}

.status-card {
  .status-content {
    display: flex;
    flex-direction: column;
    .status-info {
      display: flex;
      flex-direction: column;
      .status-title {
        margin: 20rpx 0;
        font-size: 36rpx;
      }
      .status-lable {
        font-size: 28rpx;
        color: #999;
      }
    }
    .status-divider {
      margin: 20rpx 0;
    }

    .status-meta {
      display: flex;
      font-size: 24rpx;
      line-height: 1.8;
      text-align: center;
      opacity: 0.9;
      .status-item {
        display: flex;
        flex: 1;
        flex-direction: column;
        color: #666;
        .action-icon {
          font-size: 42rpx;
        }
        .action-text {
          font-size: 20rpx;
        }
      }
    }
  }
}

.address-section {
  .address-card {
    .address-header {
      display: flex;
      align-items: center;
      padding-bottom: 20rpx;
      border-bottom: 1rpx solid #eee;

      .title {
        margin-left: 10rpx;
        font-size: 28rpx;
        color: #333;
      }
    }

    .address-body {
      padding-top: 20rpx;
      font-size: 28rpx;

      .name {
        margin-right: 30rpx;
      }
      .detail {
        display: block;
        margin-top: 15rpx;
        color: #666;
      }
    }
  }
}

.goods-section {
  .goods-list {
    .goods-item {
      display: flex;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #eee;

      &:last-child {
        border: none;
      }

      .goods-thumb {
        width: 120rpx;
        height: 120rpx;
        margin-right: 20rpx;
        border-radius: 8rpx;
      }

      .goods-info {
        flex: 1;
        width: 220rpx;
        .goods-info-one {
          display: flex;
          justify-content: space-between;
          .goods-info-price {
            display: flex;
            flex-direction: column;
            .sale-price {
              padding-right: 20rpx;
              font-size: 28rpx;
              font-weight: 600;
              color: #333;
              &::before {
                font-size: 20rpx;
                content: '￥';
              }
            }
            .market-price {
              padding-right: 20rpx;
              font-size: 22rpx;
              color: #999;
              text-decoration: line-through;
              &::before {
                font-size: 20rpx;
                content: '￥';
              }
            }
          }
        }
        .name {
          display: -webkit-box;
          width: 300rpx;
          overflow: hidden;
          font-size: 28rpx;
          color: #666;
          text-overflow: ellipsis;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }

        .quantity {
          font-size: 24rpx;
          color: #666;
        }
      }
    }
  }

  .expand-btn {
    padding: 20rpx;
    font-size: 28rpx;
    color: #999;
    text-align: center;
  }

  .discount-info {
    margin-top: 30rpx;

    .discount-item {
      display: flex;
      justify-content: space-between;
      padding: 15rpx 0;
      font-size: 24rpx;
      color: #666;

      .value {
        font-size: 32rpx;
        color: #e4393c;
      }
    }

    .total-line {
      display: flex;
      justify-content: space-between;
      padding-top: 20rpx;
      margin-top: 20rpx;
      border-top: 1rpx solid #eee;

      .total {
        margin-bottom: 20rpx;
        font-size: 32rpx;
        color: #e4393c;
      }
    }
  }
}

.order-section {
  .order-info {
    color: #333;
    .custom-cell-group {
      overflow: hidden;
      background-color: #fff;
      border-radius: 8px;
    }

    .custom-cell {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #eee;
    }

    .custom-cell:last-child {
      border-bottom: none;
    }

    .cell-title {
      font-size: 24rpx;
      color: #333;
    }

    .cell-value {
      font-size: 24rpx;
      color: #666;
    }
  }
}
.section {
  padding: 20rpx;
  margin: 20rpx 0;
  background: #fff;
  border-radius: 16rpx;
}
</style>
